package com.weike.wk_android;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.trello.rxlifecycle3.components.RxActivity;
import com.weike.wk_android.model.UserInfo;
import com.weike.wk_android.utils.ActivityStackManager;
import com.weike.wk_android.utils.BaseObserver;
import com.weike.wk_android.model.Version;
import com.weike.wk_android.utils.RetrofitUtils;
import com.weike.wk_android.utils.RxHelper;
import com.weike.wk_android.widget.toast.MyToast;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends RxActivity {
    public static final String TAG = "MainActivity";

    @BindView(R.id.btn_get)
    Button btnGet;
    @BindView(R.id.btn_get_version)
    Button btnGetVersion;
    @BindView(R.id.btn_get_login)
    Button btnGetLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_main);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_get, R.id.btn_get_version, R.id.btn_get_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_get:
                get();
                break;
            case R.id.btn_get_version:
//                getVersion();
//                getVersionWithRxJava();
//                getLastVersion();
                getLastVersionWithRxJava();
                break;
            case R.id.btn_get_login:
//                getLogin();
//                getLoginWithGet();
                getLoginWithRxJava();
                break;
        }
    }

    private void get() {
        Log.e(TAG, "TopActivity --> " + ActivityStackManager.getInstance().getTopActivity());
        Log.e(TAG, "CurrentActivity --> " + ActivityStackManager.getInstance().getCurrentActivity());
    }

    private void getLoginWithRxJava() {
        Map<String, String> map = new HashMap<>();
        map.put("username", "18916916840");
        map.put("password", "aa000000");
        RetrofitUtils.getApi().loginWithRxJava("18916916840", "aa000000")
                .compose(RxHelper.observableIO2Main(this))
                .subscribe(new Observer<UserInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UserInfo UserInfo) {
                        MyToast.showHMToast(MainActivity.this, false, UserInfo.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getLastVersionWithRxJava() {
        RetrofitUtils.getApi().getLastVersionWithRxJava2()
                .compose(RxHelper.observableIO2Main(this))
                .subscribe(new BaseObserver<Version>() {
                    @Override
                    protected void onSuccess(Version version) {
                        MyToast.showHMToast(MainActivity.this, true, version.toString());
                    }

                    @Override
                    protected void onFailure(Throwable e, String err_mag) {
                        Log.i(TAG, "onFailure: " + err_mag);
                    }
                });
    }

    private void getLastVersion() {
        RetrofitUtils.getApi().getLastVersionWithRxJava()
                .compose(RxHelper.observableIO2Main(this))
                .subscribe(new Observer<Version>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.e(TAG, "onSubscribe: ------ >>> " );
            }

            @Override
            public void onNext(Version version) {
                Log.e(TAG, "onNext: ---- >>>>>" + version);
            }

            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "onError: ---- >>>>>" + e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.e(TAG, "onComplete: ----- >>>>> ");
            }
        });
    }

    /**
     * 获取登陆信息
     */
    private void getLoginWithGet() {
        Map<String, String> map = new HashMap<>();
        map.put("username", "18916916840");
        map.put("password", "aa000000");

        RetrofitUtils.getApi().loginWithGet(map).enqueue(new Callback<UserInfo>() {
            @Override
            public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
                Toast.makeText(MainActivity.this, response.body().toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<UserInfo> call, Throwable t) {

            }
        });
    }

    /**
     * 获取登录信息
     */
    private void getLogin() {
        RetrofitUtils.getApi().login("18916916840", "aa000000").enqueue(new Callback<UserInfo>() {
            @Override
            public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
                Toast.makeText(MainActivity.this, response.body().toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<UserInfo> call, Throwable t) {

            }
        });
    }

    /**
     * 获取服务器版本信息
     */
    private void getVersion() {
        RetrofitUtils.getApi().getLastVersion().enqueue(new Callback<Version>() {
            @Override
            public void onResponse(Call<Version> call, Response<Version> response) {
                Toast.makeText(MainActivity.this, response.body().toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<Version> call, Throwable t) {

            }
        });
    }

    public void getVersionWithRxJava(){
        // 使用RxJava步骤(第一种)
        // 1. 创建Observable主题(被观察者)
        // 2. 创建Observer观察者
        // 3. 添加主题的订阅(被观察者的订阅功能给与观察者)
        Observable<Version> observable = getObservable();
        Observer<Version> observer = getObserver();

        // 第一种添加主题订阅
        // 如果不加上subscribeOn，subscribe(),onNext()方法等都是在主线程中进行，所以处理耗时操作时需要将他们放置在io，
        // 如果此时在onNext()方法对视图进行操作时，需要放在主线程中observeOn
//        observable
//                .subscribeOn(Schedulers.io())       // 将subscribe的耗时操作放在io线程中操作
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(observer);

        // 第二种添加主题订阅
        observable.compose(RxHelper.observableIO2Main(this))
                .subscribe(new Consumer<Version>() {
            @Override
            public void accept(Version version) throws Exception {
                MyToast.showToast(MainActivity.this, version.toString());
            }
        });
    }

    private Observer<Version> getObserver() {
        return
        new Observer<Version>() {
            @Override
            public void onSubscribe(Disposable d) {
//                d.dispose();    //  移除订阅关系
//                d.isDisposed();     // 判断是否仍是订阅关系
                Log.e(TAG, "onSubscribe: --------- >>>" );
            }

            @Override
            public void onNext(Version version) {
                MyToast.showToast(MainActivity.this, version.toString());
                Log.e(TAG, "onNext: " + version);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                Log.e(TAG, "onError: ----- >>>> " + e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.e(TAG, "onComplete: ------------  >>>> ");
            }
        };
    }

    private Observable<Version> getObservable() {

        // 第二种创建Observable主题
//        Observable<Version> observable = Observable.just(new Version());
//        return  observable;
        // 第一种创建Observable主题
        return Observable.create(new ObservableOnSubscribe<Version>() {
            @Override
            public void subscribe(ObservableEmitter<Version> emitter) throws Exception {
                // body().string()方法只能调用一次，多次调用会出现异常
//                Log.e(TAG, "subscribe: ----- >>>>" + api.getLastVersion().execute().body());
                Version version = RetrofitUtils.getApi().getLastVersion().execute().body();
                emitter.onNext(version);
                emitter.onComplete();
            }
        });
    }
}
